package io.renren.handler;

import io.renren.entity.WxUser;
import io.renren.service.WxUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Slf4j
@Component
public class UnsubscribeHandler extends AbstractHandler {

    @Autowired
    private WxUserService wxUserService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context,
                                    WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        String openId = wxMessage.getFromUser();
        log.info("取消关注用户 OPENID: " + openId);
        //查询用户消息
        Map query = new HashMap();
        query.put("openId",wxMessage.getFromUser());
        List<WxUser> userList = wxUserService.queryList(query);

        if (userList != null && userList.size() > 0) {
            WxUser wxUser = userList.get(0);
            wxUser.setSubscribe("2");
            wxUser.setUpdateTime(new Date());
            wxUserService.update(wxUser);
        }

        return null;
    }

}
